﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using TestDatabase.Properties;

namespace TestDatabase
{
    public partial class fMain : Form
    {
        private const int MAX_CHECK_CNT = 2;

        private static Settings appSettings = new Settings();
        private DataSet dsData = new DataSet();
        private DataLogic.FVE fveData = new DataLogic.FVE();

        private ResourceManager m_resourceManager = null;
        private DateTime[] absentDates;

        private string[] colNames = new string[] { "value1", "value2", "value3", "value4", "value5", "value6", "value7", "value8", "value9", "value10" };

        //private String databaseFileName = appSettings.DatabaseFileName;

        public fMain()
        {
            //Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("cs-CZ");

            InitializeComponent();

        	tpSetup.Hide();
        	tpDebug.Hide();
        	tabControl1.SelectedTab = tpData;
            
        	cbStridac.SelectedIndex = 0;
        	cbDataFVE.SelectedIndex = 0;

            OpenData();

            LoadConfigurationValues();

            Localize();

            //dbgData.DataSource = DataLogic.FVE_data.DayTable;
        }

        private void OpenData()
        {
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

            try
            {
                fveData.OpenDatabase("fve.db");
                MarkDates();
                SelectTab(tpData);
            }
            finally
            {
                System.Windows.Forms.Cursor.Current = Cursors.Default;
            }
        }

        private void LoadConfigurationValues()
        {
            string selectedValues = (string)GetFromRegistry("selectedValues");

            if (!string.IsNullOrEmpty(selectedValues))
            {
                string[] checkedIndicies = selectedValues.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i1 = 0; i1 < checkedIndicies.Length; i1++)
                {
                    int idx;
                    if ((int.TryParse(checkedIndicies[i1], out idx)) && (clGraphValues.Items.Count >= (idx + 1)))
                    {
                        clGraphValues.SetItemChecked(idx, true);
                    }
                }
            }

            //chart1.Series[0].XValueType = ChartValueType.Time;
            //chart1.ChartAreas[0].AxisX.IsStartedFromZero = true;
            //chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH";
            //chart1.ChartAreas[0].AxisX.Interval = 1800;
            //chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
            //chart1.ChartAreas[0].AxisX.IntervalOffset = 0;
        }

        private void SaveConfigurationValues()
        {
            //Microsoft.Win32.RegistryKey configRegistryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\FveMonitor");
            //string selectedValues = configRegistryKey != null ? (string)configRegistryKey.GetValue("selectedValues", String.Empty) : String.Empty;

            string idx = string.Empty;

            for (int i1 = 0; i1 < clGraphValues.CheckedIndices.Count; i1++)
                idx += (string.IsNullOrEmpty(idx) ? string.Empty : ",") + Convert.ToString(clGraphValues.CheckedIndices[i1]);

            SetToRegistry("selectedValues", idx);
        }

        private object GetFromRegistry(string registryKeyName)
        {
            Microsoft.Win32.RegistryKey configRegistryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\FveMonitor");
            var ret = configRegistryKey != null ? configRegistryKey.GetValue(registryKeyName, null) : null;
            configRegistryKey.Close();

            return ret;
        }

        private void SetToRegistry(string registryKeyName, object registryKeyValue)
        {
            Microsoft.Win32.RegistryKey configRegistryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\FveMonitor");
            configRegistryKey.SetValue(registryKeyName, registryKeyValue);
            configRegistryKey.Close();
        }

        private void Localize()
        {
            m_resourceManager = new ResourceManager("TestDatabase.TestDatabase", Assembly.GetExecutingAssembly());
            
            this.Text = m_resourceManager.GetString("Application Description");

            this.tsbExit.Text = m_resourceManager.GetString("Exit");
            this.tsbAddData.Text = m_resourceManager.GetString("Add data");
            this.tsbData.Text = m_resourceManager.GetString("Data");
            this.tsbGraph.Text = m_resourceManager.GetString("Graph");
            this.tsbCalendar.Text = m_resourceManager.GetString("Calendar");
            this.tsbSettings.Text = m_resourceManager.GetString("Settings");
            this.tsbDebug.Text = m_resourceManager.GetString("Debug");
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }

        private void button2_Click(object sender, EventArgs e)
        {
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show(this, m_resourceManager.GetString("End of Application"), m_resourceManager.GetString("Question"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) e.Cancel = true;

            SaveConfigurationValues();
        }

        private void tsbExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void tpDebug_Click(object sender, EventArgs e)
        {

        }

        private void tsbData_Click(object sender, EventArgs e)
        {
            //dbgData.DataSource = fveData.GetDayData();
            SelectTab(tpData);
        }

        private void SelectTab(TabPage tp)
        {
            tabControl1.SelectedTab = tp;
            clGraphValues.Visible = (tabControl1.SelectedTab == tpGraph);
        }

        private void tsbDebug_Click(object sender, EventArgs e)
        {
            SelectTab(tpDebug);
        }

        private void tsbGraph_Click(object sender, EventArgs e)
        {
            EnableSeries();
            SelectTab(tpGraph);
        }

        private void tsbAddData_Click(object sender, EventArgs e)
        {
            //Microsoft.Win32.RegistryKey configRegistryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\FveMonitor");
            //folderBrowserDialog1.SelectedPath = configRegistryKey != null ? (string)configRegistryKey.GetValue("selectDirectory", String.Empty) : String.Empty; ;
            
            folderBrowserDialog1.SelectedPath = (string)GetFromRegistry("selectDirectory");

            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                String[] allfiles = System.IO.Directory.GetFiles(folderBrowserDialog1.SelectedPath, "int_kwr_*.txt", System.IO.SearchOption.AllDirectories);

                tbDebug.Clear();
                Progress prog = new Progress();

                try
                {
                    prog.MaxProgress = allfiles.Count();
                    prog.Show(this);

                    //for (int i = allfiles.Count() - 1; i > -1; i--)
                    //{
                    //    prog.Description = Path.GetFileName(allfiles[i]);
                    //    prog.ActualProgress++;

                    //    tbDebug.Text += String.Format("{0}{1}", allfiles[i], Environment.NewLine);

                    //    System.Threading.Thread.Sleep(500);
                    //}

                    var tran = fveData.Connection.BeginTransaction();

                    foreach (string fileName in allfiles)
                    {
                        prog.Description = Path.GetFileName(fileName);
                        prog.ActualProgress++;

                        tbDebug.Text += String.Format("{0}{1}", fileName, Environment.NewLine);

                        //System.Threading.Thread.Sleep(500);
                        fveData.GetData(fileName, tran);
                    }

                    tran.Commit();
                }
                finally
                {
                    prog.Close();
                    MarkDates();

                    //configRegistryKey.SetValue("selectDirectory", folderBrowserDialog1.SelectedPath);
                    //configRegistryKey.Close();
                    
                    SetToRegistry("selectDirectory", folderBrowserDialog1.SelectedPath);
                }
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
        }

        private void button3_Click(object sender, EventArgs e)
        {
        }

        private void button4_Click(object sender, EventArgs e)
        {
        }

		void MarkDates()
		{
			absentDates = fveData.GetDateList().AsEnumerable().Select(r => r.Field<DateTime>("file_date")).ToArray();
			monthCalendar1.BoldedDates = absentDates;
		}
		
		void MonthCalendar1DateSelected(object sender, DateRangeEventArgs e)
		{
			if (absentDates.Contains(monthCalendar1.SelectionRange.Start))
			{
                System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

                try
                {
                    dbgData.DataSource = fveData.GetDayData(monthCalendar1.SelectionRange.Start, cbStridac.SelectedIndex + 1, cbDataFVE.SelectedIndex + 1);
                    FillGraphValues();
                }
                finally
                {
                    System.Windows.Forms.Cursor.Current = Cursors.Default;
                }
			}
		}

        private void FillGraphValues()
        {
            if (clGraphValues.CheckedIndices.Count == 0) return;

            DataView firstView = new DataView((DataTable)dbgData.DataSource);

            int ItemIdx = 0;

            foreach (var item in clGraphValues.Items)
            {
                if (item.Equals(clGraphValues.CheckedItems[0])) break;
                ItemIdx += 1;
            }

            chart1.Series[0].Points.DataBindXY(firstView, "date_time", firstView, colNames[ItemIdx]);

            if (clGraphValues.CheckedIndices.Count > 1)
            {
                ItemIdx = 0;

                foreach (var item in clGraphValues.Items)
                {
                    if (item.Equals(clGraphValues.CheckedItems[1])) break;
                    ItemIdx += 1;
                }

                chart1.Series[1].Points.DataBindXY(firstView, "date_time", firstView, colNames[ItemIdx]);
            }

            //chart1.ChartAreas[0].AxisX.RoundAxisValues(); 
            
            EnableSeries();
        }

        private void EnableSeries()
        {
            chart1.Visible = !(clGraphValues.CheckedIndices.Count == 0);
            if (!chart1.Visible) return;

            chart1.Series[0].Enabled = clGraphValues.CheckedIndices.Count > 0;
            chart1.Series[1].Enabled = clGraphValues.CheckedIndices.Count > 1;
        }
		
		void DbgDataCellContentClick(object sender, DataGridViewCellEventArgs e)
		{
	
		}
		
		public static DateTime ChangeTime(DateTime dateTime, int hours = 0, int minutes = 0, int seconds = 0, int milliseconds = 0)
		{
		    return new DateTime(
		    	dateTime.Year,
		    	dateTime.Month,
		    	dateTime.Day,
		    	hours,
		    	minutes,
		    	seconds,
		    	milliseconds,
		    	dateTime.Kind);
		}

        private void clGraphValues_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Checked && clGraphValues.CheckedItems.Count >= MAX_CHECK_CNT)
            {
                clGraphValues.ItemCheck -= clGraphValues_ItemCheck;
                clGraphValues.SetItemChecked(clGraphValues.CheckedIndices[0], false);
                clGraphValues.ItemCheck += clGraphValues_ItemCheck;
            }

            FillGraphValues();
        }

        private void clGraphValues_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillGraphValues();
            //EnableSeries();
        }
    }
}